package fasilkom.antz.background;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.InputStream;

import alqs.tiled.TiledMap;
import alqs.tiled.UnsupportedFormatException;

import com.golden.gamedev.engine.BaseLoader;
import com.golden.gamedev.util.ImageUtil;


/**
 * Kelas ini mengimplementasikan {@link TiledMap} sebagai TMX map loader/reader. 
 * 
 * @see TiledBackground
 *
 */
public class Map extends TiledMap<BufferedImage, BufferedImage[]> {

	protected BaseLoader bsLoader;
	
	public Map(BaseLoader bsLoader, String fileName) {
		this.bsLoader = bsLoader;
		this.load(loadStream(fileName), fileName.substring(0, fileName.lastIndexOf('/')));
	}

	@Override
	protected BufferedImage[] createImageCollection(String fileName, int tileWidth,
			int tileHeight, int tileSpacing, int tileMargin,
			String transparentHex, Dimension tilesCount) {
		if (tileSpacing != 0 || tileMargin != 0)
			throw new UnsupportedFormatException("Non-0 tile spacing or margin is not supported (yet)");
		
		// Load main image
		BufferedImage mainImage;
		if (transparentHex == null) {
			mainImage = bsLoader.getImage(fileName);
		} else {
			Color oldMask = bsLoader.getMaskColor();
			bsLoader.setMaskColor(new Color(Integer.parseInt(transparentHex, 16)));
			mainImage = bsLoader.getImage(fileName, true);
			bsLoader.setMaskColor(oldMask);
		}
		
		// Get vertical & horizontal count and split
		tilesCount.width = mainImage.getWidth() / tileWidth;
		tilesCount.height = mainImage.getHeight() / tileHeight;
		BufferedImage[] images = ImageUtil.splitImages(mainImage,
				tilesCount.width, tilesCount.height);
		
//		Sprite[] result = new Sprite[images.length];
//		for (int i = 0; i < images.length; ++i) {
//			result[i] = new Sprite(images[i]);
//		}
		return images;
	}

	@Override
	protected BufferedImage getImage(int x, int y, BufferedImage[] images, int cols, int rows) {
		return images[x + y * cols];
	}

	@Override
	protected InputStream loadStream(String fileName) {
		return bsLoader.getBaseIO().getStream(fileName);
	}
}
